package com.enhanced.mqtt.client;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.UUID;

/**
 * 多协议MQTT客户端示例
 * 演示如何使用不同协议（TCP、WebSocket）连接到EMQX
 */
public class MultiProtocolClient {
    
    private static final String TCP_URL = "tcp://192.168.3.234:1883";
    private static final String WS_URL = "ws://192.168.3.234:8083/mqtt";
    private static final String WSS_URL = "wss://192.168.3.234:8084/mqtt";
    private static final String TOPIC = "test/protocol";
    private static final int QOS = 1;
    
    public static void main(String[] args) {
        try {
            runDemo(new Scanner(System.in));
        } catch (Exception e) {
            System.out.println("MQTT错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 运行演示，使用外部传入的Scanner
     * @param scanner 已经打开的Scanner
     */
    public static void runDemo(Scanner scanner) throws Exception {
        System.out.println("=== 多协议连接示例 ===");
        System.out.println("本示例演示如何使用不同协议连接到EMQX服务器");
        System.out.println("1. TCP连接 - " + TCP_URL);
        System.out.println("2. WebSocket连接 - " + WS_URL);
        System.out.print("请选择连接协议(1-2): ");
        
        int choice = scanner.nextInt();
        scanner.nextLine(); // 消费换行符
        
        String brokerUrl;
        String clientPrefix;
        
        if (choice == 2) {
            brokerUrl = WS_URL;
            clientPrefix = "WSClient";
            System.out.println("选择了WebSocket连接");
        } else {
            brokerUrl = TCP_URL;
            clientPrefix = "TCPClient";
            System.out.println("选择了TCP连接");
        }
        
        // 创建客户端
        String clientId = clientPrefix + "-" + System.currentTimeMillis();
        MqttAsyncClient client = new MqttAsyncClient(brokerUrl, clientId, new MemoryPersistence());
        
        // 设置回调
        client.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable cause) {
                System.out.println("连接丢失: " + cause.getMessage());
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) {
                String payload = new String(message.getPayload());
                System.out.println("\n收到消息:");
                System.out.println("  主题: " + topic);
                System.out.println("  内容: " + payload);
                System.out.println("  QoS: " + message.getQos());
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                System.out.println("消息发送完成");
            }
        });
        
        // 连接选项
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(true);
        
        // 连接服务器
        System.out.println("正在连接到MQTT服务器: " + brokerUrl);
        client.connect(options).waitForCompletion();
        System.out.println("已连接到MQTT服务器，客户端ID: " + clientId);
        
        // 订阅主题
        client.subscribe(TOPIC, QOS).waitForCompletion();
        System.out.println("已订阅主题: " + TOPIC);
        
        // 发送消息
        String message = "这是一条通过" + (choice == 2 ? "WebSocket" : "TCP") + "协议发送的消息";
        MqttMessage mqttMessage = new MqttMessage(message.getBytes());
        mqttMessage.setQos(QOS);
        client.publish(TOPIC, mqttMessage).waitForCompletion();
        System.out.println("已发送消息");
        
        // 等待接收消息
        System.out.println("等待5秒接收消息...");
        Thread.sleep(5000);
        
        // 断开连接
        client.disconnect().waitForCompletion();
        System.out.println("已断开连接");
        
        // 不关闭scanner，由调用者负责关闭
    }
    
    /**
     * 创建不验证证书的SSLSocketFactory
     */
    public static javax.net.ssl.SSLSocketFactory getSocketFactoryWithoutVerification() throws Exception {
        javax.net.ssl.SSLContext sslContext = javax.net.ssl.SSLContext.getInstance("TLSv1.2");
        sslContext.init(null, null, null);
        return sslContext.getSocketFactory();
    }
} 